<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
use App\Components\Tools;

use App\Components\DyToools;
use App\Models\DyModels\Douyin;
/**
 * 获取抖音授权用户视频
 */
class DyUserVideo extends Command{
  /**
   * The name and signature of the console command.
   *
   * @var string
   */
  protected $signature = 'DyUserVideo';

  /**
   * The console command description.
   *
   * @var string
   */
  protected $description = '获取抖音授权用户视频';
  
  /**
   * Execute the console command.
   *
   * @return mixed
   */
  public function handle(){
    //$this->getDyUserVideo();
    Tools::commandsLog('DyUserVideo:'.date("Y-m-d H:i:s"));       
    $this->nowVideo();
 
  }
  
  
  	//	查询指定视频数据  （审核视频 或者 已发布的视频最新数据）------------------------------------------------------------------------------------------------------
	//查询要更新的视频 --- 去重 open_id
	function nowVideo(){
		$userVideo=new Douyin();
		$videoList=$userVideo->examineVideo();
		if($videoList){
			foreach($videoList as $k=>$v){
				$this->findVideoList($v['open_id']);
			}
		}
	}
	//查询指定 open_id 的视频数据 及 授权信息
	function findVideoList($open_id){
		$userVideo=new Douyin();
		$videoList=$userVideo->findVideo($open_id);
		if($videoList){
			$item_ids=array(
			    'item_ids'=>array(),
			);
			foreach($videoList as $k=>$v){
				$item_ids["item_ids"][]=$v['item_id'];
			}
			$this->apiVideoData($item_ids,$open_id);
		}
	}
	//上调接口请求查询视频数据
	function apiVideoData($item_ids,$open_id){
		$infoToken=new Douyin();
		$DyToools=new DyToools();
		
		$token=$infoToken->oneTokenInfo($open_id);
		$url =  Tools::getOneconfig("/config/third.json",array('douyin','dy_url'));
		$url=$url ."/video/data?open_id={$token['open_id']}&access_token={$token['access_token']}";
		$dataList=$this->postJson($url,$item_ids); 
		if( isset($dataList['data']['error_code']) && $dataList['data']['error_code']==0 && isset($dataList['data']['list']) ){
			
			//得到视频数据更新到数据库
			$this->upVideoList($dataList['data']['list']);
			
			
		}elseif( isset($dataList['data']['error_code']) && ($dataList['data']['error_code']==10008 || $dataList['data']['error_code']==2190008) ){
			
			
			// access_token 过期
			$dataOne=$DyToools->refresh_token($token['refresh_token']);
			if($dataOne['data']['error_code']==0){
				
				
				//更新数据库的 access_token
				$infoToken->upToken($dataOne['data'],$open_id);
				//重新调用上调接口
				$this->apiVideoData($item_ids,$open_id);
				
				
			}elseif( isset($dataList['data']['error_code']) &&$dataOne['data']['error_code']==10010 ){
				
				
				//refresh_token 过期
				$dataTwo=$DyToools->renew_refresh_token($token['refresh_token']);
				if( isset($dataList['data']['error_code']) &&$dataTwo['data']['error_code']==0 ){
					
					
					//更新数据库的 refresh_token
					$infoToken->upRef($dataTwo['data'],$open_id);
					//重新调用上调接口
					$this->apiVideoData($item_ids,$open_id);
					
					
				}else{
					$infoToken->upTokenStatus($open_id);//授权过期需用户重新授权 更改授权状态 为 0
				}
			}
		}
	}
	//视频数据更新
	function upVideoList($data){
		$upVideo=new Douyin();
		if($data){
			foreach($data as $k=>$v){
				$status=1;$remark="";
				if($v['is_reviewed'] && $v['video_status']==1){
					$status=2;
				}elseif($v['is_reviewed'] && $v['video_status']==2){
					$remark="不宜公开";
				}
				$arr=array(
					'title'=>htmlspecialchars($v['title'],ENT_QUOTES),
					'talk'=>'',
					'is_reviewed'=>$v['is_reviewed'],
					'is_top'=>$v['is_top'],
					'video_status'=>$v['video_status'],
					'status'=>$status,
					'update_time'=>date('Y-m-d H:i:s',time()),
					'comment_count'=>$v['statistics']['comment_count'],
					'digg_count'=>$v['statistics']['digg_count'],
					'download_count'=>$v['statistics']['download_count'],
					'play_count'=>$v['statistics']['play_count'],
					'share_count'=>$v['statistics']['share_count'],
					'forward_count'=>$v['statistics']['forward_count'],
					'remark'=>$remark,
				);
				if($status==2){
					$arr['cover']=$v['cover'];
					$arr['share_url']=$v['share_url'];
				}
				if($v['is_reviewed']){
					$upVideo->upVideoInfo($arr,$v['item_id']);
				}
			}
		}
	}

  
 	//post请求
	function postJson($url, $data = array()){
		//初始化
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
		curl_setopt($curl, CURLOPT_HEADER, 0);
		//超时时间
		curl_setopt($curl, CURLOPT_TIMEOUT,60);
		//设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//设置post方式提交
		curl_setopt($curl, CURLOPT_POST, 1);
		//设置post数据
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Content-Length: ' . strlen(json_encode($data)))
		);

		//执行命令
		$json = curl_exec($curl);
		//关闭URL请求
		curl_close($curl);
		return json_decode($json, true);
	} 
  
  
  //before 
  public function getDyUserVideo(){
    $syncing = DB::table('pt_dy_infosync')->select('id','partner_id','is_video')->where('status',1)->first();
    if(empty($syncing)){  //没有进行中的才执行
      $tosync = DB::table('pt_dy_infosync')->select('id','partner_id','is_video')->where('status',0)->first();
      if(!empty($tosync)){
        $oInfoSync = new \App\Models\DyModels\Infosync();
        $oInfoSync->db_update('',$tosync['id'],['status'=>1]);
        if($tosync['is_video'] == 1){ //如果视频已同步
          $oInfoSync->db_update('',$tosync['id'],['status'=>2]);
        }else{
          $oUser = new \App\Models\UserModels\User();
          $uData = $oUser->db_get(['partner_id'=>['=',1]]);
          $oDyAccessToken = new \App\Models\UserModels\DyAccessToken();
          $atData = $oDyAccessToken->db_get(['partner_id'=>['=',1]]);
          if(!empty($uData) && !empty($atData)){
            $this->saveData($uData,$atData,0,10);
          }
          $oInfoSync->db_update('',$tosync['id'],['status'=>2,'is_video'=>1]);
        }
      }
    }
  }
  
  public function saveData($uData,$atData,$cursor,$count){
    $result = \App\Components\DyVideoTools::searchVideoList($atData['access_token'],$uData['open_id'],$cursor,$count);
    if($result['error_code'] == 0){
      if(!empty($result['list'])){
        foreach($result['list'] as $val){
          $this->userVideoSave($val,$uData['partner_id']);
        }
      }
      if($result['has_more']){//如果还有更多
        $cursor++;
        $this->saveData($uData,$atData,$cursor,$count);
      }
    }else if($result['error_code'] == 10008 || $result['error_code'] == 2190008){ //access_token已过期
      $reData = \App\Components\DyTools::refreshToken($atData['refresh_token']);
      if($reData['error_code'] == 0){
        $oDyAccessToken = new \App\Models\UserModels\DyAccessToken();
        $oDyAccessToken->db_update('',$atData['id'],[
          'expires_in' => $reData['expires_in'],
          'refresh_expires_in' => $reData['refresh_expires_in'],
          'refresh_token'=> $reData['refresh_token'],
          'scope' => $reData['scope'],
          'access_token' => $reData['access_token'],
          'update_time' => date('Y-m-d H:i:s')
        ]);
        $atData2 = $oDyAccessToken->db_get(['id'=>['=',$atData['id']]]);
        $this->saveData($uData,$atData2,$cursor,$count);
      }else if($reData['error_code'] == 10010){//refresh_token过期
        $rerftData = \App\Components\DyTools::renewRefreshToken($atData['refresh_token']);
        $oDyAccessToken = new \App\Models\UserModels\DyAccessToken();
        if($rerftData['error_code'] == 0){
          $oDyAccessToken->db_update('',$atData['id'],[
            'refresh_expires_in' => $reData['expires_in'],
            'refresh_token'=> $reData['refresh_token'],
            'update_time' => date('Y-m-d H:i:s')
          ]);
          $atData3 = $oDyAccessToken->db_get(['id'=>['=',$atData['id']]]);
          $this->saveData($uData,$atData3,$cursor,$count);
        }else{//需要用户重新授权
          $oDyAccessToken->db_update('',$atData['id'],[
            'update_time' => date('Y-m-d H:i:s'),
            'status' => 0
          ]);
        }
      }
    }
  }
  
  public function userVideoSave($val,$partner_id){
    $oUserVideo = new \App\Models\DyModels\UserVideo();
    $uvData = $oUserVideo->db_get(['item_id'=>['=',$val['item_id']],'partner_id'=>['=',$partner_id]]);
    $data = [];
    $data['cover'] = $val['cover'];
    $data['is_top'] = $val['is_top'] ? 1 : 0;
    $data['share_url'] = $val['share_url'];
    $data['title'] = $val['title'];
    $data['is_reviewed'] = $val['is_reviewed'] ? 1 : 0;
    $data['digg_count'] = $val['statistics']['digg_count'];
    $data['download_count'] = $val['statistics']['download_count'];
    $data['forward_count'] = $val['statistics']['forward_count'];
    $data['play_count'] = $val['statistics']['play_count'];
    $data['share_count'] = $val['statistics']['share_count'];
    $data['comment_count'] = $val['statistics']['comment_count'];
    $data['video_status'] = $val['video_status'];
    $data['update_time'] = date('Y-m-d H:i:s');
    if(!empty($uvData)){
      $oUserVideo->db_update('',$uvData['id'],$data);
    }else{
      $data['partner_id'] = $partner_id;
      $data['item_id'] = $val['item_id'];
      $data['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
      $oUserVideo->db_insert($data);
    }
  }
}
